<template>
  <div class="app-container">
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="580px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        style="margin-left: 20px"
        v-show="showSearch"
        label-width="90px"
      >
        <el-col :span="24">
          <el-form-item label="销售单号" prop="somDjbh">
            <el-input
              v-model="queryParams.somDjbh"
              placeholder="请输入销售单号"
              clearable
              style="width: 400px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="客户编码" prop="somCustwldm">
            <el-input
              v-model="queryParams.somCustwldm"
              clearable
              placeholder="请输入客户编码"
              style="width: 400px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发货时间" prop="dateRange">
            <el-date-picker
              clearable
              size="small"
              v-model="dateRange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="订单状态" prop="somZtbz">
            <el-radio-group v-model="queryParams.somOrderZtbz">
              <el-radio
                v-for="dict in somOrderZtbzOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="display: flex; margin-top: 20px; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          v-hasPermi="['produce:materialMatain:query']"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="single"
          @click="handleAdd"
          v-hasPermi="['produce:materialMatain:add']"
        >
          单个材料明细维护
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="multiple"
          @click="handleMultAdd"
          v-hasPermi="['produce:materialMatain:Multadd']"
        >
          批量材料明细维护
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      highlight-current-row
      v-loading="loading"
      :data="somList"
      border
      stripe
      :height="tableH"
      @scrollBottom="load"
      @row-click="getAlreadyMatain"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="#" type="index" width="55" align="center" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="销售单号"
        :show-overflow-tooltip="true"
        min-width="20%"
        align="center"
        prop="somDjbh"
      />
      <el-table-column
        label="客户"
        :show-overflow-tooltip="true"
        min-width="20%"
        align="center"
        prop="somKhdm"
      >
        <template #default="scope">
          <dict-tag :options="customerOptions" :value="scope.row.somKhdm" />
        </template>
      </el-table-column>
      <el-table-column
        label="客户编码"
        min-width="20%"
        align="center"
        :show-overflow-tooltip="true"
        prop="somCustwldm"
      />
      <el-table-column
        label="本厂物料"
        :show-overflow-tooltip="true"
        min-width="20%"
        align="center"
        prop="somWldm"
      />
      <el-table-column
        label="品名规格"
        min-width="40%"
        :show-overflow-tooltip="true"
        prop="somPmgg"
      />
      <el-table-column
        label="订单数量"
        :show-overflow-tooltip="true"
        min-width="20%"
        align="center"
        prop="somDdsl"
      />
      <el-table-column
        label="交货日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="somJhrq"
        min-width="20%"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.somJhrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        :show-overflow-tooltip="true"
        min-width="20%"
        align="center"
        prop="remark"
      />
    </el-table>

    <div style="border: 1px solid white; margin-top: 1px"></div>

    <el-table
      highlight-current-row
      :data="molList"
      border
      stripe
      :height="tableHChild"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="#" type="index" width="55" align="center" />
      <el-table-column
        label="父项代码"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="molFxdm"
      />
      <el-table-column
        label="客户编码"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="molCustomerCode"
      />
      <el-table-column
        label="物料代码"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="molWldm"
      />
      <el-table-column
        label="品名规格"
        :show-overflow-tooltip="true"
        width="320"
        prop="molPmgg"
      />
      <el-table-column
        label="单位"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="molDw"
      >
        <template #default="scope">
          <dict-tag :options="itmDwOptions" :value="scope.row.molDw" />
        </template>
      </el-table-column>
      <el-table-column
        label="采购属性"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="molCgsx"
      >
        <template #default="scope">
          <dict-tag :options="bomCgsxOptions" :value="scope.row.molCgsx" />
        </template>
      </el-table-column>
      <el-table-column
        label="订单数量"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="molDdsl"
      />
      <el-table-column
        label="单位用量"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="molDwyl"
      />
      <el-table-column
        label="水口重量"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="molSkzl"
      />
      <el-table-column
        label="固定损耗%"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="molGdsh"
      />
      <el-table-column
        label="需求数量"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="molXqsl"
      />
      <el-table-column
        label="建立人员"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="createBy"
      />
      <el-table-column
        label="建立日期"
        :show-overflow-tooltip="true"
        width="150"
        align="center"
        prop="createTime"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="审核人员"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="molShry"
      />
      <el-table-column
        label="审核日期"
        :show-overflow-tooltip="true"
        width="150"
        align="center"
        prop="molShrq"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.molShrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        width="80"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            :disabled="scope.row.molZtbz === 2 || scope.row.molQrsl > 0"
            icon="el-icon-delete"
            @click="handleMolDelete(scope.row)"
            v-hasPermi="['produce:materialMatain:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改营销订单维护对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :fullscreen="true"
      append-to-body
    >
      <el-table
        highlight-current-row
        :data="NoneMaintain"
        :height="tabled"
        @selection-change="handleSelectionChangeChild"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="父项代码"
          :show-overflow-tooltip="true"
          align="center"
          prop="molFxdm"
        />
        <el-table-column
          label="客户编码"
          :show-overflow-tooltip="true"
          align="center"
          prop="molCustomerCode"
        />
        <el-table-column
          label="物料代码"
          :show-overflow-tooltip="true"
          align="center"
          prop="molWldm"
        />
        <el-table-column
          label="品名规格"
          :show-overflow-tooltip="true"
          align="center"
          prop="molPmgg"
        />
        <el-table-column
          label="单位"
          :show-overflow-tooltip="true"
          align="center"
          prop="molDw"
        >
          <template #default="scope">
            <dict-tag :options="itmDwOptions" :value="scope.row.molDw" />
          </template>
        </el-table-column>
        <el-table-column
          label="采购属性"
          :show-overflow-tooltip="true"
          align="center"
          prop="molCgsx"
        >
          <template #default="scope">
            <dict-tag :options="bomCgsxOptions" :value="scope.row.molCgsx" />
          </template>
        </el-table-column>
        <el-table-column
          label="订单数量"
          :show-overflow-tooltip="true"
          align="center"
          prop="molDdsl"
        />
        <el-table-column
          label="单位用量"
          :show-overflow-tooltip="true"
          align="center"
          prop="molDwyl"
        />
        <el-table-column
          label="水口重量"
          :show-overflow-tooltip="true"
          align="center"
          prop="molSkzl"
        />
        <el-table-column
          label="固定损耗%"
          :show-overflow-tooltip="true"
          align="center"
          prop="molGdsh"
        />
        <el-table-column
          label="需求数量"
          :show-overflow-tooltip="true"
          align="center"
          prop="molXqsl"
        />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSom, delSom, addSom, updateSom } from "@/api/marketing/som";

import { getAllCustomer } from "@/api/project/customer";
import { getItmMstrByCustwldm } from "@/api/project/materiel";
import {
  batchSubmitMol,
  deleteMol,
  getAlreadyMol,
  getMaterielMatainSom,
  getWaitMol,
  submitMol,
} from "@/api/produce/materialMatain";
import { getAllCgList } from "@/api/project/mstr";

export default {
  name: "MaterialMatain",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],

      //子项Mol数组
      molList: [],
      tableH: (document.body.clientHeight - 180) / 2,
      tableHChild: (document.body.clientHeight - 180) / 2,
      tabled: document.body.clientHeight - 200,
      //用来保存的Mol数组
      saveMolList: [],

      somDjbhs: [],

      //当前数据
      currentData: [],

      //采购属性
      bomCgsxOptions: [],

      //未维护的材料明细
      NoneMaintain: [],
      //保存当前Som
      somData: [],
      // 日期范围
      dateRange: [
        this.$moment().startOf("month").toDate(),
        this.$moment().add(100, "year").endOf("month").toDate(),
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 营销订单维护表格数据
      somList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSearch: false,
      // 状态标志字典
      somZtbzOptions: [],
      //根据客户代码查询出物料信息
      selectedItmMstr: [],
      // 订单类型字典
      somOrderZtbzOptions: [],
      //单位类型字典
      itmDwOptions: [],

      //客户类型
      customerOptions: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        somDjbh: null,
        somCustwldm: null,
        somOrderZtbz: "1",
        somJhrqEnd: null,
        somJhrqBegin: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.getList();

    //得到单位
    this.getDicts("sys_unit").then((response) => {
      this.itmDwOptions = response.data;
    });

    //得到客户
    getAllCustomer().then((response) => {
      for (let i of response.data) {
        i.dictLabel = i.cusName;
        i.dictValue = i.cusCode + "";
        i.listClass = "default";
      }
      this.customerOptions = response.data;
    });
    //得到维护类型
    this.getDicts("material_matain_ztbz").then((response) => {
      this.somOrderZtbzOptions = response.data;
    });

    //得到采购属性
    getAllCgList().then((response) => {
      this.bomCgsxOptions = response.data;
      for (let i of this.bomCgsxOptions) {
        i.dictLabel = i.cgName;
        i.dictValue = i.cgId + "";
        i.listClass = "default";
      }
    });
  },
  methods: {
    /** 查询营销订单维护列表 */
    getList(row) {
      if (this.dateRange !== null) {
        this.queryParams.somJhrqBegin = this.moment(this.dateRange[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.queryParams.somJhrqEnd = this.moment(this.dateRange[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      } else {
        this.queryParams.somJhrqBegin = null;
        this.queryParams.somJhrqEnd = null;
      }
      this.loading = true;
      this.queryParams.pageNum = 1;
      getMaterielMatainSom(this.queryParams).then((response) => {
        this.somList = [];
        this.somList = this.somList.concat(response.rows);
        this.total = response.total;
        this.loading = false;

        if (row) {
          this.getAlreadyMatain(row);
        } else if (this.somList.length > 0) {
          this.getAlreadyMatain(this.somList[0]);
        } else {
          this.molList = [];
        }
      });
    },
    load() {
      if (
        this.queryParams.pageNum <
        Math.ceil(this.total / this.queryParams.pageSize)
      ) {
        // this.$message.success("加载下一页")
        this.queryParams.pageNum++;
        getMaterielMatainSom(this.queryParams).then((response) => {
          this.somList = this.somList.concat(response.rows);
          this.total = response.total;
          this.loading = false;
          if (row) {
            this.getAlreadyMatain(row);
          } else if (this.somList.length > 0) {
            this.getAlreadyMatain(this.somList[0]);
          } else {
            this.molList = [];
          }
        });
      }
      return 0;
    },
    //获取已经维护的子项
    getAlreadyMatain(row) {
      this.somData = row;

      if (row) {
        //请求后台拿到已经维护的材料明细
        getAlreadyMol(row.somDjbh).then((response) => {
          this.molList = response.data;
        });
      }
    },

    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        somId: null,
        somDjbh: null,
        somCustwldm: null,
        somWldm: null,
        somDdsl: null,
        somKhdm: null,
        somXdrq: new Date(),
        somJhrq: new Date(),
        somKykc: null,
        remark: null,
        somZtbz: null,
        createBy: null,
        createTime: null,
        somShry: null,
        somShrq: null,
        somJary: null,
        somJarq: null,
        somType: null,
        somChsl: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = null;
      this.queryParams.somJhrqBegin = null;
      this.queryParams.somJhrqEnd = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.somId);
      this.somDjbhs = selection.map((item) => item.somDjbh);
      this.currentData = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    //对话框多选框选中数据
    handleSelectionChangeChild(selection) {
      this.saveMolList = selection;
    },
    handleSearch() {
      this.reset();
      this.title = "查询材料明细维护";
      this.openSearch = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.currentData.length > 0) {
        getWaitMol(this.currentData[0].somDjbh).then((response) => {
          this.NoneMaintain = response.data;
          this.title = "材料明细维护";
          this.open = true;
        });
      }
    },

    /** 提交按钮 */
    submitForm() {
      if (this.saveMolList.length > 0) {
        submitMol(this.saveMolList).then((response) => {
          this.msgSuccess("维护成功");

          this.open = false;

          this.getAlreadyMatain(this.somData);
        });
      }
    },
    /** 删除按钮操作 */
    handleMolDelete(row) {
      //如果已经申请，则不允许删除
      if (row.molQrsl > 0) {
        this.msgError("材料已经申购，不允许删除");
      } else {
        const molId = row.molId;
        const molWldm = row.molWldm;
        this.$confirm("确认删除明细[" + molWldm + "]?删除不可恢复", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            return deleteMol(molId);
          })
          .then(() => {
            this.getAlreadyMatain(this.somData);
            this.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },

    //批量材料明细维护
    handleMultAdd() {
      if (this.queryParams.somOrderZtbz == "3") {
        this.msgError("材料已经审核，不允许再次维护");
      } else {
        const molWldm = this.somDjbhs;
        this.$confirm("确认维护明细[" + molWldm + "]?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return batchSubmitMol(molWldm);
          })
          .then(() => {
            this.getAlreadyMatain(this.somData);
            this.msgSuccess("维护成功");
          })
          .catch(() => {});
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
